//
//  EventViewController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/24/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "EventViewController.h"
#import "Extensions.h"
#import "EventDetailViewController.h"
#import "CreateEventViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "EventFilterViewController.h"

#define kEDistance 1
#define kETime 2
#define kETitle 3
#define kEDescription 4

enum {
  
    DataSourceAll = 0,
    DataSourceAttending = 1,
    DataSourceMyEvent = 2 
};

@interface NSDate (GTM)

- (NSDate*)GTM;

@end

@implementation NSDate (GTM)

- (NSDate*)GTM
{
    NSDate *date = nil;
    
    if (self != nil && [self isKindOfClass:[NSDate class]]) {
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
        NSString *stringDate = [dateFormatter stringFromDate:self];
        date = [dateFormatter dateFromString:stringDate];
    }
    
    return date;
}

@end

@implementation EventViewController

@synthesize bottomBarView;
@synthesize isRefresh;
@synthesize mode = _mode;
@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Private Method

- (void)applyAppearance
{
    self.bottomBarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bottom-bar.png"]];
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"filter-button" 
                                 target:self 
                                 action:@selector(filter:)];
    
    [self setLeftButtonImageActiveName:nil 
                          inactiveName:@"btn_home" 
                                target:self 
                                action:@selector(back:)];
    [self setTitle:@"Events"];
    
    [self.tableView setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg"]]];
}

- (CGFloat)heighForEventDescription:(NSDictionary*)event
{
    NSString *description = [event objectForKey:@"event_description"];
    CGFloat hDesc = [JGoUtility heightFromString:description maxWidth:234 font:JGO_FONT_HELVETICA(12)];
    
    return hDesc;
}

- (void)filter
{
    if (_lastFilter == nil) {
        return;
    }
    
    NSArray *filters = [_lastFilter componentsSeparatedByString:@";"];
    
    if ([filters count] < 3) {
        return;
    }
    
    NSInteger whenFilter = [[filters objectAtIndex:0] integerValue];
    NSInteger whatFilter = [[filters objectAtIndex:1] integerValue];
    NSInteger onlaFilter = [[filters objectAtIndex:2] integerValue];
    
    if (whenFilter == 0 && whatFilter == 0 && onlaFilter == 0) {
        return;
    }
    
    NSMutableArray *todayEvent = [dataSource objectForKey:@"today"];
    NSMutableArray *upcomingEvents = [dataSource objectForKey:@"upcoming"];
    
    if (whenFilter == 2) {
        [dataSource setValue:nil forKey:@"today"];
        
        for (int iup = 0; iup < [upcomingEvents count]; iup++) {
            
            NSDictionary *aEvent = [upcomingEvents objectAtIndex:iup];
            NSInteger eventType = [[aEvent objectForKey:@"event_type"] integerValue];
            NSInteger eventScope = [[aEvent objectForKey:@"event_scope"] integerValue];
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];
            
            if ([JGoUtility daysBetweenDate:[NSDate date] andDate:eventDate] != 1) {
                [upcomingEvents removeObject:aEvent];
                iup--;
                continue;
            }
            
            if (whatFilter == 1) {
                
                if (eventType != 2) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 2) {
                
                if (eventType != 1) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 3) {
                
                if (eventType != 0) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 1) {
                
                if (eventScope != 1) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 2) {
                
                if (eventScope != 0) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
        }
    }
    else if (whenFilter == 1){
        [dataSource setValue:nil forKey:@"upcoming"];
        
        for (int iup = 0; iup < [todayEvent count]; iup++) {
            
            NSDictionary *aEvent = [todayEvent objectAtIndex:iup];
            NSInteger eventType = [[aEvent objectForKey:@"event_type"] integerValue];
            NSInteger eventScope = [[aEvent objectForKey:@"event_scope"] integerValue];
            
            if (whatFilter == 1) {
                
                if (eventType != 2) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 2) {
                
                if (eventType != 1) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 3) {
                
                if (eventType != 0) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 1) {
                
                if (eventScope != 1) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 2) {
                
                if (eventScope != 0) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
        }
    }
    else
    {
        // Today is sure in this week, so need other filters
        
        for (int iup = 0; iup < [todayEvent count]; iup++) {
            
            NSDictionary *aEvent = [todayEvent objectAtIndex:iup];
            NSInteger eventType = [[aEvent objectForKey:@"event_type"] integerValue];
            NSInteger eventScope = [[aEvent objectForKey:@"event_scope"] integerValue];
            
            if (whatFilter == 1) {
                
                if (eventType != 2) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 2) {
                
                if (eventType != 1) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 3) {
                
                if (eventType != 0) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 1) {
                
                if (eventScope != 1) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 2) {
                
                if (eventScope != 0) {
                    [todayEvent removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
        }

        // Upcoming filter
        
        for (int iup = 0; iup < [upcomingEvents count]; iup++) {
            
            NSDictionary *aEvent = [upcomingEvents objectAtIndex:iup];
            NSInteger eventType = [[aEvent objectForKey:@"event_type"] integerValue];
            NSInteger eventScope = [[aEvent objectForKey:@"event_scope"] integerValue];
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];            
            NSInteger thisWeek = [JGoUtility weekOfYearFromDate:[NSDate date]];
            NSInteger eventWeek = [JGoUtility weekOfYearFromDate:eventDate];
            
            if (eventWeek != thisWeek) {
                [upcomingEvents removeObject:aEvent];
                iup--;
                continue;
            }
            
            if (whatFilter == 1) {
                
                if (eventType != 2) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 2) {
                
                if (eventType != 1) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (whatFilter == 3) {
                
                if (eventType != 0) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 1) {
                
                if (eventScope != 1) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
            
            if (onlaFilter == 2) {
                
                if (eventScope != 0) {
                    [upcomingEvents removeObject:aEvent];
                    iup--;
                    continue;
                }
            }
        }
    }
}

- (void)selectDataSource:(NSInteger)aSourceType
{
    [dataSource release];
    
    dataSource = [NSMutableDictionary new];
    NSMutableArray *todayEvents = [[NSMutableArray new] autorelease];
    NSMutableArray *upcomingEvents = [[NSMutableArray new] autorelease];
    
    [dataSource setValue:todayEvents forKey:@"today"];
    [dataSource setValue:upcomingEvents forKey:@"upcoming"];
    
    if (aSourceType == 0) {
        
        for (NSDictionary *aEvent in myEvents) {
            
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];
            
            if ([JGoUtility daysBetweenDate:[NSDate date] andDate:eventDate] == 0) {
                [todayEvents addObject:aEvent];
            }
            else {
                [upcomingEvents addObject:aEvent];
            }
        }
        
        for (NSDictionary *aEvent in myAttending) {
            
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];
            
            if ([JGoUtility daysBetweenDate:[NSDate date] andDate:eventDate] == 0) {
                [todayEvents addObject:aEvent];
            }
            else {
                [upcomingEvents addObject:aEvent];
            }
        }
        
        for (NSDictionary *aEvent in myPending) {
            
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];
            [aEvent setValue:@"1" forKey:@"Pending"];
            
            if ([JGoUtility daysBetweenDate:[NSDate date] andDate:eventDate] == 0) {
                [todayEvents addObject:aEvent];
            }
            else {
                [upcomingEvents addObject:aEvent];
            }
        }               
    }
    
    if (aSourceType == 1) {
        
        for (NSDictionary *aEvent in myAttending) {
            
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];
                                   
            if ([JGoUtility daysBetweenDate:[NSDate date] andDate:eventDate] == 0) {
                [todayEvents addObject:aEvent];
            }
            else {
                [upcomingEvents addObject:aEvent];
            }
        }        
    }
    
    if (aSourceType == 2) {
        
        for (NSDictionary *aEvent in myEvents) {
            
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];            
            
            if ([JGoUtility daysBetweenDate:[NSDate date] andDate:eventDate] == 0) {
                [todayEvents addObject:aEvent];
            }
            else {
                [upcomingEvents addObject:aEvent];
            }
        }        
    }
    
    [self filter];
}

#pragma mark - View lifecycle
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (isRefresh) {
        isRefresh = NO;
        [JGoUtility showProgressInView:self.view 
                                target:self 
                                 title:@"Reloading..."
                              selector:@selector(delayLoadEvents:)];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self applyAppearance];
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Loading Events..."
                          selector:@selector(delayLoadEvents:)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)dealloc
{
    [dataSource release];
    [myEvents release];
    [myAttending release];
    [myPending release];
    [super dealloc];
}

- (UITableViewCell*)createEventCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"EventCell" owner:nil options:nil];
    
    return (id)[views objectAtIndex:0];
}

#pragma mark - Action

-(IBAction)CreateEventPressed:(id)sender 
{
    CreateEventViewController *ceVC = [[[CreateEventViewController alloc] initWithNibName:@"CreateEventViewController"
                                                                                   bundle:nil] autorelease];
    self.isRefresh = YES;
    [self.navigationController pushViewController:ceVC animated:YES];
}

- (IBAction)AttendingPressed:(id)sender 
{
    [self selectDataSource:DataSourceAttending];
    [self.tableView reloadData];
}

- (IBAction)MyEventsPressed:(id)sender 
{
    [self selectDataSource:DataSourceMyEvent];
    [self.tableView reloadData];    
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)filter:(id)sender
{
    EventFilterViewController *efVC = [[[EventFilterViewController alloc] initWithNibName:@"EventFilterViewController"
                                                                                   bundle:nil] autorelease];
    
    [efVC setDelegate:(id)self];
    [efVC setLastFilter:_lastFilter];
    [self.navigationController pushViewController:efVC animated:YES];
}

#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *todayEvents = [dataSource objectForKey:@"today"];
    NSArray *upcomingEvents = [dataSource objectForKey:@"upcoming"];
    
    if (section == 0) {
        return [todayEvents count];
    }
    
    return [upcomingEvents count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSArray *todayEvents = [dataSource objectForKey:@"today"];
    NSArray *upcomingEvents = [dataSource objectForKey:@"upcoming"];
    
    switch (section) {
        case 0: {
            return ([todayEvents count] ? @"Today" : nil);
        }
        case 1: {
            return ([upcomingEvents count] ? @"Upcoming" : nil);
        }          
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *aEvent = nil;
    
    switch (indexPath.section) {
        case 0: {
            NSArray *todayEvents = [dataSource objectForKey:@"today"];
            aEvent = [todayEvents objectAtIndex:indexPath.row];            
            
            break;
        }
        case 1: {
            NSArray *upcomingEvents = [dataSource objectForKey:@"upcoming"];            
            aEvent = [upcomingEvents objectAtIndex:indexPath.row];            
            
            break;
        }
    }        
    
    CGFloat hDesc = [self heighForEventDescription:aEvent];
    
    if (hDesc >= 30) {
        return 96;
    }
    
    return 66;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSDictionary *aEvent = nil;
    CGFloat hDesc = 0;
    NSString *eventTime = nil;
    
    cell = [tableView dequeueReusableCellWithIdentifier:@"EventCell"];
    
    if (cell == nil) {
        cell = [self createEventCellFromNib];
    }        
    
    UIView *flagView = [cell viewWithTag:5];  
    UIImageView *attendingView = (id)[flagView viewWithTag:6];
    
    switch (indexPath.section) {
        case 0: {
            NSArray *todayEvents = [dataSource objectForKey:@"today"];
            aEvent = [todayEvents objectAtIndex:indexPath.row];  
            eventTime = [NSString stringWithFormat:@"Today, %@ - %@",
                         [JGoUtility longTimeToShortTime:[aEvent objectForKey:@"start_time"]],
                         [JGoUtility longTimeToShortTime:[aEvent objectForKey:@"end_time"]]];
            
            if (indexPath.row == 0) {                              
                flagView.layer.cornerRadius = 10;
                flagView.clipsToBounds = YES;                
            }
                        
            if (indexPath.row % 2 == 0) {
                cell.backgroundColor = [UIColor colorWithRed:241./255 green:250./255 blue:254./255 alpha:1];
            }
            else {
                cell.backgroundColor = [UIColor colorWithRed:254./255 green:246./255 blue:254./255 alpha:1];
            }
            
            if ([[aEvent objectForKey:@"Pending"] integerValue] > 0) {
               
                attendingView.image = [UIImage imageNamed:@"event-plum"];
            }
            else {
                attendingView.image = [UIImage imageNamed:@"event-blue"];
            }
            
            break;
        }
        case 1: {
            NSArray *upcomingEvents = [dataSource objectForKey:@"upcoming"];            
            aEvent = [upcomingEvents objectAtIndex:indexPath.row]; 
            NSDate *eventDate = [JGoUtility dateFromString1:[aEvent objectForKey:@"event_date"]];
            NSString *dateString = [JGoUtility stringFromDate3:eventDate];            
            eventTime = [NSString stringWithFormat:@"%@, %@ - %@",dateString,
                         [JGoUtility longTimeToShortTime:[aEvent objectForKey:@"start_time"]],
                         [JGoUtility longTimeToShortTime:[aEvent objectForKey:@"end_time"]]];
            
            if (indexPath.row == 0) {                
                flagView.layer.cornerRadius = 10;
                flagView.clipsToBounds = YES;
            }
            
            
            if (indexPath.row % 2 == 0) {
                cell.backgroundColor = [UIColor colorWithRed:241./255 green:250./255 blue:254./255 alpha:1];
            }
            else {
                cell.backgroundColor = [UIColor colorWithRed:254./255 green:246./255 blue:254./255 alpha:1];
            }
            
            if ([[aEvent objectForKey:@"Pending"] integerValue] > 0) {
                
                attendingView.image = [UIImage imageNamed:@"event-plum"];
            }
            else {
                attendingView.image = [UIImage imageNamed:@"event-blue"];
            }
            
            break;
        }
    }
    
    [cell.contentView setAutoresizesSubviews:NO];
    [cell titleTextWithTag:kETitle].text = [aEvent objectForKey:@"event_title"];
    [cell titleTextWithTag:kEDescription].text = [aEvent objectForKey:@"event_description"]; 
    [cell titleTextWithTag:kETime].text = eventTime;        
    [cell titleTextWithTag:kEDistance].text = [JGoUtility distanceString:[aEvent objectForKey:@"event_distance"]];
    
    UILabel *descritionUI = [cell titleTextWithTag:kEDescription];
    hDesc = [self heighForEventDescription:aEvent];    
    
    if (hDesc >= 30 && hDesc < 45 ) {        
        CGRect newRect = descritionUI.frame;
        newRect.origin.y = 40;
        newRect.size.height = 42;
        descritionUI.lineBreakMode = UILineBreakModeWordWrap;
        descritionUI.numberOfLines = 2;
        descritionUI.frame = newRect;
    }
    else if (hDesc >= 45) {
        CGRect newRect = descritionUI.frame;
        newRect.origin.y = 36;        
        newRect.size.height = 63;
        descritionUI.lineBreakMode = UILineBreakModeWordWrap;
        descritionUI.numberOfLines = 3;  
        descritionUI.frame = newRect;        
    }
    else {
        CGRect newRect = descritionUI.frame;
        newRect.origin.y = 40;        
        newRect.size.height = 21;
        descritionUI.lineBreakMode = UILineBreakModeWordWrap;
        descritionUI.numberOfLines = 1;  
        descritionUI.frame = newRect;          
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];    
    NSDictionary *aEvent = nil;
    
    switch (indexPath.section) {
        case 0: {
            NSArray *todayEvents = [dataSource objectForKey:@"today"];
            aEvent = [todayEvents objectAtIndex:indexPath.row];  
            break;
        }
        case 1: {
            NSArray *upcomingEvents = [dataSource objectForKey:@"upcoming"];            
            aEvent = [upcomingEvents objectAtIndex:indexPath.row]; 
            break;
        }
    }
    
    if (self.mode == EventForNormal) {
        EventDetailViewController *edVC = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController"
                                                                                       bundle:nil] autorelease];
        [edVC setDelegate:(id)self];
        [edVC setEvent:aEvent];
        [self.navigationController pushViewController:edVC animated:YES];
    }
    else if (self.mode = EventForShare) {
        
        if ([_delegate respondsToSelector:@selector(eventViewController:didSelectedWithEvent:)]) {
            [_delegate eventViewController:self didSelectedWithEvent:aEvent];
        }
    }
}

#pragma mark - Delay Method

- (void)delayLoadEvents:(MBProgressHUD*)progress
{
    NSError *error = nil;
    NSDictionary *events = nil;
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    
    events = [JGoAPI getEventsWithUserId:userId 
                                     lat:[JGoUtility sharedLatitude]
                                     lon:[JGoUtility sharedLongitude]
                                   error:&error];
    
    if (!error) {        
        
        [dataSource release];
        [myEvents release];
        [myAttending release];
        [myPending release];
        
        dataSource = nil;
        myEvents = nil;
        myAttending = nil;
        myPending = nil;
        
        myEvents = [[events objectForKey:@"MyEvent"] retain];
        myAttending = [[events objectForKey:@"MyAttending"] retain];
        myPending = [[events objectForKey:@"MyPending"] retain];
        
        [self selectDataSource:DataSourceAll];        
        [self.tableView reloadData];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}

#pragma mark - Event Detail Delegate

- (void)eventDetailViewController:(EventDetailViewController*)edVC event:(NSDictionary*)event isDeleted:(BOOL)isDeleted
{
    isRefresh = YES;
}

#pragma mark - Event Filter Delegate

- (void)eventFilterViewController:(EventFilterViewController*)efVC lastFilter:(NSString*)lastFilter
{
    [_lastFilter release];
    _lastFilter = [lastFilter retain];
    
    [self selectDataSource:DataSourceAll];
    [self.tableView reloadData];
}

@end
